<template>
  <div class="user">
    <!--    功能区域-->
    <div style="margin: 10px 0">
      <el-button type="primary" @click="addUser">新增用户</el-button>
    </div>

    <!--    搜索区域-->
    <div style="margin: 10px 0">
      <el-input
        style="width: 20%"
        placeholder="请输入关键字"
        prefix-icon="el-icon-search"
        clearable
        v-model="search">
      </el-input>

      <el-button type="primary" plain @click="searchUser">搜索</el-button>
    </div>


    <!--    内容区域-->
    <!--    stripe：添加斑马纹-->
    <el-table
      :data="tableData"
      stripe
      border
      style="min-width: calc(100vh - 200px)"
    >
      <!--      sortable：给日期一个排序按钮-->


      <el-table-column
        label="序号"
        type="index">
      </el-table-column>

      <el-table-column
        prop="username"
        label="用户名">

      </el-table-column>


      <el-table-column label="角色">
        <template v-slot="scope">
          <span v-if="scope.row.roles===1">管理员</span>
          <span v-else>普通用户</span>
        </template>
      </el-table-column>


      <el-table-column
        prop="nickName"
        label="昵称">

      </el-table-column>

      <el-table-column
        prop="age"
        label="年龄">

      </el-table-column>

      <el-table-column
        prop="sex"
        label="性别">

      </el-table-column>


      <el-table-column
        prop="address"
        label="地址">
      </el-table-column>

      <el-table-column label="操作" width="400">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="success"
            @click="showNews(scope.row)">查看新闻列表
          </el-button>

          <el-button
            size="mini"
            @click="handleEdit(scope.row)">编辑
          </el-button>

          <el-popconfirm
            @confirm="deleteUser(scope.row.id)"
            confirm-button-text='好的'
            cancel-button-text='不用了'
            icon="el-icon-info"
            icon-color="red"
            title="确认删除吗？"
          >
            <el-button size="mini" type="danger" slot="reference">删除</el-button>
          </el-popconfirm>

        </template>
      </el-table-column>

    </el-table>

    <div style="margin: 10px 0">

      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[5, 10, 20]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>

    </div>

    <!--    新增用户的表单-->
    <el-dialog title="请输入用户信息" :visible.sync="dialogVisible" width="30%">
      <el-form :rules="rules" ref="form" :model="form" label-width="120px">

        <el-form-item label="用户名：" prop="username">
          <el-input v-model="form.username" style="width: 70%"></el-input>
        </el-form-item>


        <el-form-item label="昵称：">
          <el-input v-model="form.nickName" style="width: 70%"></el-input>
        </el-form-item>

        <el-form-item
          label="年龄："
          prop="age"
        >
          <el-input style="width: 70%" placeholder="默认可以为空" v-model.number="form.age" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="性别：">
          <el-radio v-model="form.sex" label="男">男</el-radio>
          <el-radio v-model="form.sex" label="女">女</el-radio>
        </el-form-item>

        <el-form-item label="地址：">
          <el-input type="textarea" v-model="form.address" style="width: 70%"></el-input>
        </el-form-item>

        <el-form-item label="角色：">
          <el-radio v-model="form.roles" :label=1>管理员</el-radio>
          <el-radio v-model="form.roles" :label=2>普通用户</el-radio>
        </el-form-item>

      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="save(form)">确 定</el-button>
  </span>
    </el-dialog>


    <!--查看用户发布的news-->
    <el-dialog :title="authorTop" :visible.sync="showNewsDialog" width="70%">
      <el-table
        :data="details"
        stripe
        border
      >

        <el-table-column
          prop="author"
          label="发布者">
        </el-table-column>

        <el-table-column
          prop="title"
          label="标题">
        </el-table-column>

        <el-table-column
          prop="time"
          label="发布时间">
        </el-table-column>


        <el-table-column label="内容">

          <template v-slot="scope">

            <el-card>
              <div v-html="scope.row.content" style="min-height: 150px"></div>
            </el-card>



          </template>


        </el-table-column>


      </el-table>


    </el-dialog>

  </div>
</template>

<script>
import request from "../unitls/request";

export default {
  name: 'User',
  //利用声明周期函数 加载数据
  created() {
    this.load();
  },
  methods: {

    //新增按钮
    addUser() {
      //点击了新增按钮，设置变量为true，打开表单页面
      this.dialogVisible = true;
      //打开则清空表单
      this.form = {};
    },

    //新增和编辑
    save(form) {
      console.log(123)
      //增加验证年龄功能
      this.$refs.form.validate((valid) => {
        console.log(this.form)
        if (valid) {
          if (this.form.id) {
            request.put("/api/user", this.form).then(success => {
              this.load();
              this.dialogVisible = false;
              if (success.code === '0') {
                this.$notify({
                  title: '更新成功',
                  message: success.data + '更新成功！',
                  type: 'success'

                });
              } else {
                this.$notify({
                  title: '更新失败',
                  message: success.msg,
                  type: 'error'

                });
              }

            })
          } else {
            request.post("/api/user", this.form).then(success => {
              this.load();
              this.dialogVisible = false;
              console.log(success);
              if (success.code === '0') {
                this.$notify({
                  title: '插入成功',
                  message: success.data + '插入成功！',
                  type: 'success'
                });
              } else {
                this.$notify({
                  title: '插入失败',
                  message: success.msg,
                  type: 'error'

                });
              }
            })
          }

        } else {
          return false;
        }
      });


      /**/


    },
    //查询数据
    load() {
      request.get("/api/user", {

        params: {
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          searchStr: this.search
        }


      }).then(success => {
        this.tableData = success.data.records;
        this.total = success.data.total;

      })
    },

    //模糊查询
    searchUser() {
      this.load();
    },

    //查看新闻列表
    showNews(row) {
      this.authorTop =row.username+' 发布的新闻';
      this.showNewsDialog = true;
      if (row.username) {
        request.get("/api/news/queryNews", {
          params: {
            author: row.username
          }
        }).then(success => {
          this.details = success.data;
        })
      }
    },

    //编辑
    handleEdit(row) {
      //将传过来的row深拷贝给form
      this.form = JSON.parse(JSON.stringify(row));
      console.log(this.form)
      this.dialogVisible = true;
    },


    //改变当前页的数据个数
    handleSizeChange(val) {
      this.pageSize = val
      this.load();
    },

    //改变当前页的页码
    handleCurrentChange(val) {
      this.currentPage = val;
      this.load();
    },


    //删除
    deleteUser(val) {
      request.delete("/api/user", {

        params: {
          id: val
        }

      }).then(success => {
        if (success.code === '0') {
          this.$notify({
            title: '删除成功',
            message: '用户已被删除',
            type: 'success'
          });

          //解决删除当前页最后一条数据后，页面无法跳转的问题
          const totalPage = Math.ceil((this.total - 1) / this.pageSize);
          this.currentPage = this.currentPage > totalPage ? totalPage : this.currentPage;
          this.currentPage = this.currentPage < 1 ? 1 : this.currentPage;
          this.load();


        } else {
          this.$notify({
            title: '删除失败',
            message: '用户未被删除',
            type: 'success'

          });
        }

        this.load();

      })
    }

  },
  data() {
    //验证年龄
    let checkAge = (rule, value, callback) => {
      if (value) {
        setTimeout(() => {
          if (value.length !== 0 && !Number.isInteger(value)) {
            callback(new Error('请输入数字值'));
          } else if (value > 120 || value < 0) {

            callback(new Error('年龄必须在 1 到 120 之间'));
          }
          callback();
        }, 100)

      }
      callback();
      // return callback(new Error('年龄不能为空'));
    };
    return {
      //form 新增数据的表单
      form: {},
      //表单是否打开
      dialogVisible: false,
      //富文本的详情
      details: [],
      //查看用户发布的新闻时，顶层显示的用户名
      authorTop:'',
      //查看用户发布的新闻列表
      showNewsDialog: false,
      //搜索
      search: '',
      //当前页
      currentPage: 1,
      //一页有多少条数据
      pageSize: 10,
      //数据总数
      total: 0,
      //后端传过来的数据
      tableData: [],
      //定义规则
      rules: {
        username: [
          {required: true, message: '请输入用户名', trigger: 'blur'},
          {min: 3, max: 9, message: '长度在 3 到 9 个字符', trigger: 'blur'}
        ],
        age: [
          // {required: true},
          {validator: checkAge, trigger: 'blur'}
        ]
      },

    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>

.user {
  padding: 10px;
}

</style>
